package com.sanglh.tutorial.thread;

import java.lang.reflect.Method;
import java.util.ArrayList;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;

import com.sanglh.tutorial.R;
import com.sanglh.tutorial.common.base.BaseEntry;
import com.sanglh.tutorial.common.base.BaseListAdapter;
import com.sanglh.tutorial.common.base.Logging;
import com.sanglh.tutorial.common.view.ProgressDialogFragment;

public class ThreadActivity extends ListActivity implements OnItemClickListener {
	private ArrayList<BaseEntry> entries = new ArrayList<>();
	private Object syncObject = new Object();
	private ProgressBar pb;
	MyAsyncTask myAsyncTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_thread);
		pb = (ProgressBar) findViewById(R.id.pb);
		loadData();
	}

	private void loadData() {
		entries.add(new BaseEntry("Thread", "onThread"));
		entries.add(new BaseEntry("AsyncTask", "onAsyncTask"));
		BaseListAdapter<BaseEntry> adapter = new BaseListAdapter<>(this,
				entries);
		getListView().setAdapter(adapter);
		getListView().setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			Method method = ThreadActivity.class.getDeclaredMethod(
					entries.get(position).method, new Class[] {});
			method.setAccessible(true);
			method.invoke(ThreadActivity.this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * Thread : separate thread, post : main thread synchronized (syncObject) :
	 * synchronized thread
	 * 
	 * */

	public void onThread() {
		new Thread(new Runnable() { // Separate thread

					@Override
					public void run() {
						synchronized (syncObject) {
							Logging.log("Separate thread "
									+ (Looper.myLooper() != Looper
											.getMainLooper()));
							for (int i = 0; i <= 100; i += 10) {
								try {
									Thread.sleep(1000);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								final int progress = i;
								pb.post(new Runnable() { // Main thread
									@Override
									public void run() {
										Logging.log("main thread "
												+ (Looper.myLooper() == Looper
														.getMainLooper()));
										pb.setProgress(progress);
									}
								});
							}
						}

					}
				}).start();

	}

	public void onAsyncTask() {
		myAsyncTask = new MyAsyncTask();
		myAsyncTask.execute();

	}

	private class MyAsyncTask extends AsyncTask<Void, Integer, Void> {
		private ProgressDialogFragment progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialogFragment.Builder()
					.setMessage("Processing...")
					.setCancelableOnTouchOutside(false).build();
			progressDialog.show(getFragmentManager(), "task_progress");
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			for (int i = 0; i < 100; i += 5) {
				Logging.log(" i = " + i);
				if (!isCancelled()) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					publishProgress(i);
				}
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			progressDialog.setProgress(values[0]);
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Void result) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			super.onPostExecute(result);
		}

	}

}
